package com.sh.ssao.lottery.config.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * http 客户端工具
 */
public class HttpClientUtil {
    /**
     * httpclient post方法请求
     * @param url
     * @param paramasMap
     * @return
     */
    public static Map<String,Object> httpClientPost(String url, Map<String,String> paramasMap) {
        //创建默认的httpClient实例
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //创建httpPost
        HttpPost httppost = new HttpPost(url);
//		RequestConfig config = RequestConfig.custom().setSocketTimeout(5000*6).build();
//		httppost.setConfig(config);
        //创建参数队列
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        if(paramasMap != null && paramasMap.size()>0) {
            for(String key : paramasMap.keySet()) {
                formparams.add(new BasicNameValuePair(key, paramasMap.get(key)));
            }
        }

        UrlEncodedFormEntity uefEntity;
        CloseableHttpResponse httpResponse = null;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "utf-8");

            httppost.setEntity(uefEntity);
            System.out.println("发送地址："+httppost.getURI());
            httpResponse = httpclient.execute(httppost);

            HttpEntity httpEntity = httpResponse.getEntity();
            if(null != httpEntity) {
                String resultMsg = EntityUtils.toString(httpEntity,"utf-8");
                Map<String,Object> dataMap = new ObjectMapper().readValue(resultMsg, Map.class);
                httpResponse.close();
                httpclient.close();
                return dataMap;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    public static void main(String[] args) {
        Map<String,String> paramasMap = new HashMap<>();
        paramasMap.put("list","sh000001,sh000002,sh000003,sz399001,sz399002,sz399003,sz399005,sz399006,sh000300,sh000016,sh000011,sh600000,sh601211,sh600018");
        Map<String,Object> map = HttpClientUtil.httpClientPost("http://hq.sinajs.cn/",paramasMap);
        System.out.println(map.toString());
    }

    public static void httpClentGet() {
    }
}
